<template>
  <ContentDetailWrap :title="t('common.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form
      class="flex flex-wrap form-container"
      :model="state.form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="25%"
    >
      <el-form-item
        :label="t('productMerge.productname')"
        class="w-50%"
        prop="productname"
        required
      >
        <el-input
          v-model="state.form.productname"
          :placeholder="'请输入' + t('productMerge.productname')"
          @blur="handleBlurProductname"
        />
      </el-form-item>
      <el-form-item
        :label="t('productMerge.producturlname')"
        class="w-50%"
        prop="producturlname"
        required
      >
        <el-input
          v-model="state.form.producturlname"
          :placeholder="'请输入' + t('productMerge.producturlname')"
        />
      </el-form-item>

      <el-form-item
        :label="t('productMerge.primary_pid')"
        class="w-50%"
        prop="primary_pid"
        required
      >
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.primary_pid"
            :options="primaryPidOptions"
            :placeholder="'请选择' + t('productMerge.primary_pid')"
            clearable
            filterable
            :props="{ label: 'cname', value: 'id' }"
            @change="handlePrimarPidChange"
          />
          <el-button type="primary" @click="handleOpenPrimarPid" class="ml-2">选择</el-button>
        </div>
      </el-form-item>

      <el-form-item :label="t('productMerge.vice_pid')" class="w-50%" prop="vice_pid">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.vice_pid"
            :options="vicePidOptions"
            :props="{ label: 'cname', value: 'id' }"
            multiple
            clearable
            filterable
            @change="handleVicePidChange"
          />
          <el-button type="primary" @click="handleOpenVicePid" class="ml-2">选择</el-button>
        </div>
      </el-form-item>

      <el-form-item :label="t('productMerge.sales_pids')" class="w-50%" prop="sales_pids">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.sales_pids"
            :options="salesPidsOptions"
            :placeholder="'请选择' + t('productMerge.sales_pids')"
            multiple
            clearable
            filterable
            :props="{ label: 'cname', value: 'id' }"
            @change="handleSalesPidsChange"
          />
          <el-button type="primary" @click="handleOpenSalesPids" class="ml-2">选择</el-button>
        </div>
      </el-form-item>

      <!-- <el-form-item :label="t('productMerge.recommend_pids')" class="w-50%" prop="recommend_pids">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.recommend_pids"
            :options="recommendPidsOptions"
            :placeholder="'请选择' + t('productMerge.recommend_pids')"
            multiple
            clearable
            filterable
            :props="{ label: 'cname', value: 'id' }"
            @change="handleRecommendPidsChange"
          />
          <el-button type="primary" @click="handleOpenRecommendPids" class="ml-2">选择</el-button>
        </div>
      </el-form-item> -->

      <el-form-item :label="t('productMerge.estimate_price')" class="w-50%">
        <el-input
          v-model="state.form.estimate_price"
          type="number"
          :placeholder="'请输入' + t('productMerge.estimate_price')"
        />
      </el-form-item>

      <el-form-item
        :label="t('productMerge.product_photo')"
        :placeholder="'请输入' + t('productMerge.product_photo')"
        class="w-50%"
        prop="product_photo"
        required
      >
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 2 }"
          :limit="9"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadProductPhotoCallback"
          @handle-remove-file="handleRemoveProductPhotoFile"
          @handle-picture-card-preview="handleProductPhotoPreview"
        />
      </el-form-item>
      <el-form-item
        :label="t('productMerge.closeshots_photo')"
        :placeholder="'请输入' + t('productMerge.closeshots_photo')"
        class="w-50%"
      >
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 2 }"
          :limit="9"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCloseshotsPhotoCallback"
          @handle-remove-file="handleRemoveCloseshotsPhotoFile"
          @handle-picture-card-preview="handleCloseshotsPhotoPreview"
        />
      </el-form-item>

      <el-form-item :label="t('productMerge.pmv_id')" class="w-50%" prop="pmv_id">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.pmv_id"
            :options="pmvIdOptions"
            :placeholder="'请选择' + t('productMerge.pmv_id')"
            clearable
            filterable
            :props="{ label: 'name', value: 'id' }"
            @change="handlePmvIdChange"
          />
          <el-button type="primary" @click="handleOpenPmvId" class="ml-2">选择</el-button>
        </div>
      </el-form-item>

      <el-form-item :label="t('productMerge.smv_id')" class="w-50%" prop="smv_id">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="state.form.smv_id"
            :options="smvIdOptions"
            :placeholder="'请选择' + t('productMerge.smv_id')"
            multiple
            clearable
            filterable
            :props="{ label: 'name', value: 'id' }"
            @change="handleSmvIdChange"
          />
          <el-button type="primary" @click="handleOpenSmvId" class="ml-2">选择</el-button>
        </div>
      </el-form-item>

      <el-form-item :label="t('productMerge.storename')" class="w-50%" prop="storename">
        <el-input
          v-model="state.inputDisplayText.storename"
          disabled
          :placeholder="'请选择' + t('productMerge.storename')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenStorename"
              >选择</el-button
            >
          </template>
        </el-input>
      </el-form-item>

      <el-form-item :label="t('productMerge.seotitle')" class="w-50%" prop="seotitle" required>
        <el-input
          v-model="state.form.seotitle"
          :placeholder="'请输入' + t('productMerge.seotitle')"
        />
      </el-form-item>

      <el-form-item :label="t('productMerge.seodesc')" class="w-50%" prop="seodesc" required>
        <el-input v-model="state.form.seodesc" type="textarea" @blur="handleBlurSeodesc" />
      </el-form-item>

      <el-form-item :label="t('productMerge.describe')" class="w-50%" prop="describe" required>
        <el-input v-model="state.form.describe" type="textarea" />
      </el-form-item>
      <el-form-item :label="t('productMerge.sort')" class="w-50%" prop="sort" required>
        <el-input-number
          v-model="state.form.sort"
          :placeholder="'请输入' + t('productMerge.sort')"
          :step="1"
          :min="1"
          class="!w-70%"
        />
      </el-form-item>
      <el-form-item :label="t('productMerge.status')" class="w-50%" prop="storename">
        <el-select
          v-model="state.form.status"
          filterable
          :placeholder="'请选择' + t('productMerge.status')"
        >
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('productMerge.full_describe')" class="w-50%" prop="full_describe">
        <Editor v-model="state.form.full_describe" :editorConfig="editorConfig" />
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
  <!--  选择聚合商品的主SKU商品弹框-->
  <PrimarPidDialog ref="DialogPrimarPidCheckedRef" @expose-multiple-data="getExposePrimarPidData" />
  <!--  选择聚合商品的副SKU商品弹框-->
  <PrimarPidDialog
    ref="DialogVicePidCheckedRef"
    @expose-multiple-data="getExposeVicePidData"
    :multiple="true"
  />
  <!--  选择聚合商品的组合售卖SKU商品弹框-->
  <PrimarPidDialog
    ref="DialogSalesPidsCheckedRef"
    @expose-multiple-data="getExposeSalesPidsData"
    :multiple="true"
  />
  <!--  选择聚合商品的推荐SKU商品弹框-->
  <!-- <PrimarPidDialog
    ref="DialogRecommendPidsCheckedRef"
    @expose-multiple-data="getExposeRecommendPidsData"
    :multiple="true"
  /> -->

  <!--  选择聚合商品的商品主视频弹框-->
  <Video ref="DialogPmvIdCheckedRef" @expose-multiple-data="getExposePmvIdData" />
  <!--  选择聚合商品的商品副视频弹框-->
  <Video ref="DialogSmvIdCheckedRef" @expose-multiple-data="getExposeSmvIdData" :multiple="true" />

  <!--  选择聚合商品的店铺弹框-->
  <DialogStorename ref="DialogStorenameCheckedRef" @expose-multiple-data="getExposeStorenameData" />
</template>
<script setup lang="ts">
import PrimarPidDialog from '@/components/Dialog/src/Product.vue'
import Video from '@/components/Dialog/src/Video/Index.vue'
import DialogStorename from './components/DialogStorename/index.vue'

import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, ElMessageBox, ElLoading, type FormRules, type FormInstance } from 'element-plus'

import { getFieldEnumApi, saveDataApi, getSelectedSkuIdApi } from '@/api/productMerge'
import { CurdData } from '@/api/productMerge/types'
import { createImageViewer } from '@/components/ImageViewer'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { Editor } from '@/components/Editor' // 使用项目封装的组件
import type { IEditorConfig } from '@wangeditor/editor'
const { t } = useI18n()
const { push, go } = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const primaryPidOptions = ref<any[]>([]) // 聚合商品的主SKU商品
const vicePidOptions = ref<any[]>([]) // 聚合商品的副SKU商品
const salesPidsOptions = ref<any[]>([]) // 聚合商品的组合售卖SKU商品
// const recommendPidsOptions = ref<any[]>([]) // 聚合商品的推荐SKU商品
const pmvIdOptions = ref<any[]>([]) // 聚合商品的商品视频
const smvIdOptions = ref<any[]>([]) // 聚合商品的商品视频
const selectedSkuIds = ref<any[]>([]) // 聚合商品的已选商品ID列表
const state = reactive({
  source: route.query.source ? decodeURIComponent(route.query.source as string) : '',
  // 订单类型列表
  storenameList: ref<Array<Record<string, any>>>([]),
  // 输入显示文本
  inputDisplayText: {
    storename: '' // 聚合商品的店铺
  },

  form: ref<CurdData>({
    id: 0,
    productname: '',
    producturlname: '',
    primary_pid: null,
    vice_pid: [],
    sales_pids: [],
    estimate_price: null,
    storename: [],
    product_photo: '', // 改回数组初始化
    closeshots_photo: '',
    pmv_id: null,
    smv_id: [],
    describe: '',
    full_describe: '',
    seotitle: '',
    seodesc: '',
    views_number: 0,
    is_del: 0,
    status: '1',
    sort: 100
  }),
  product_photo_list: ref<any[]>([]), // 附件列表
  closeshots_photo_list: ref<any[]>([]) // 附件列表
})

const rules = ref<FormRules>({
  productname: [
    {
      required: true,
      message: '请输入' + t('productMerge.productname'),
      trigger: 'blur'
    }
  ],
  producturlname: [
    {
      required: true,
      message: '请输入' + t('productMerge.producturlname'),
      trigger: 'blur'
    }
  ],
  primary_pid: [
    {
      required: true,
      message: '请选择' + t('productMerge.primary_pid'),
      trigger: 'change'
    }
  ],
  product_photo: [
    {
      required: true,
      message: '请选择' + t('productMerge.product_photo'),
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (state.product_photo_list.length === 0) {
          callback(new Error('请上传至少一张图片'))
        } else {
          callback()
        }
      }
    }
  ],
  describe: [
    {
      required: true,
      message: '请输入' + t('productMerge.describe'),
      trigger: 'blur'
    }
  ],
  seotitle: [
    {
      required: true,
      message: '请输入' + t('productMerge.seotitle'),
      trigger: 'blur'
    }
  ],
  seodesc: [
    {
      required: true,
      message: '请输入' + t('productMerge.seodesc'),
      trigger: 'blur'
    }
  ]
})

// 商品名称失去焦点时，自动生成商品URL名称和SEO标题
const handleBlurProductname = () => {
  const productname = state.form.productname
  if (productname) {
    state.form.producturlname = productname
      .replace(/\s+/g, '-')
      .replace(/[^a-zA-Z0-9_-]/g, '')
      .toLowerCase()
    state.form.seotitle = productname
  }
}

// SEO描述失去焦点时，自动生成SEO标题
const handleBlurSeodesc = () => {
  const seodesc = state.form.seodesc
  if (seodesc) {
    state.form.describe = seodesc
  }
}

// 编辑器配置
const editorConfig: IEditorConfig = {
  placeholder: '请输入内容...',
  readOnly: false,
  autoFocus: false,
  scroll: true,
  customAlert: (info: string, type: 'success' | 'info' | 'warning' | 'error') => {
    ElMessage[type](info)
  },
  maxLength: 100000,
  customPaste: undefined, // 或提供自定义粘贴处理函数
  onCreated: undefined, // 或提供创建回调
  onChange: undefined, // 或提供变更回调
  onDestroyed: undefined, // 或提供销毁回调
  onFocus: undefined, // 或提供聚焦回调
  onBlur: undefined, // 或提供失焦回调
  onMaxLength: undefined, // 或提供超出长度回调
  MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.VITE_API_BASE_PATH}/common/uploadFile`,
      fieldName: 'file',
      maxFileSize: 10 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      meta: {
        folder: 'editor-images',
        directory: 2
      },
      onBeforeUpload: (file: File) => {
        console.log('上传前:', file)
        return file
      },
      onSuccess: (file: File, res: any) => {
        // 处理返回结果
        if (res.code === 0) {
          // 注意这里改为 0
          return {
            url: res.data.url, // 返回图片 URL
            alt: res.data.name || file.name, // 图片文字说明
            href: res.data.url // 点击图片跳转的链接，可选
          }
        } else {
          // 抛出错误会触发 onError
          throw new Error(res.message || '上传失败')
        }
      },
      onError: (file: File, err: Error, res?: any) => {
        console.error('上传失败:', err)
      }, // 自定义插入图片
      customInsert: (res: any, insertFn: any) => {
        // res 即上面 onSuccess 的返回结果
        console.log('customInsert res:', res)
        insertFn(res.data.url, res.data.alt, res.data.href)
      }
    }
  }
}

// 聚合商品的主SKU商品弹框 组件方法 start
const DialogPrimarPidCheckedRef = ref<InstanceType<typeof PrimarPidDialog>>()

const handleOpenPrimarPid = () => {
  nextTick(() => {
    console.log('DialogPrimarPidCheckedRef.value', DialogPrimarPidCheckedRef.value)
    if (!DialogPrimarPidCheckedRef.value) return
    DialogPrimarPidCheckedRef.value.dialogVisible = true

    const disabledVal = state.form.vice_pid
      .map((item: any) => ({ id: item }))
      .concat(state.form.sales_pids.map((item: any) => ({ id: item }))) // 副SKU商品 和 组合售卖SKU商品

    // 将 selectedSkuIds 合并到 disabledVal 并去重
    const mergedDisabledVal = [...disabledVal, ...selectedSkuIds.value]
    // 根据 id 去重
    const uniqueDisabledVal = mergedDisabledVal.filter(
      (item, index, self) => index === self.findIndex((t) => t.id === item.id)
    )
    DialogPrimarPidCheckedRef.value.initialize(
      state.form.primary_pid ? [{ id: state.form.primary_pid }] : [],
      uniqueDisabledVal //  (禁用)
    )
  })
}

const getExposePrimarPidData = (val: any[]) => {
  if (!val || !val.length) return
  primaryPidOptions.value = val
  state.form.primary_pid = val[0].id
}

const handlePrimarPidChange = (val: number) => {
  state.form.primary_pid = val
}

// 聚合商品的主SKU商品弹框 组件方法 end

// 聚合商品的副SKU商品弹框 组件方法 start
const DialogVicePidCheckedRef = ref<InstanceType<typeof PrimarPidDialog>>()

const handleOpenVicePid = () => {
  nextTick(() => {
    if (!DialogVicePidCheckedRef.value) return
    DialogVicePidCheckedRef.value.dialogVisible = true

    const disabledVal = state.form.sales_pids
      .map((item: any) => ({ id: item }))
      .concat(state.form.primary_pid ? [{ id: state.form.primary_pid }] : []) // 主SKU商品 和 组合售卖SKU商品

    // 将 selectedSkuIds 合并到 disabledVal 并去重
    const mergedDisabledVal = [...disabledVal, ...selectedSkuIds.value]
    // 根据 id 去重
    const uniqueDisabledVal = mergedDisabledVal.filter(
      (item, index, self) => index === self.findIndex((t) => t.id === item.id)
    )
    DialogVicePidCheckedRef.value.initialize(
      state.form.vice_pid ? state.form.vice_pid.map((item: any) => ({ id: item })) : [],
      uniqueDisabledVal //  (禁用)
    )
  })
}

const getExposeVicePidData = (val: any[]) => {
  if (!val || !val.length) return
  // 合并新选项和已有选项，去重
  vicePidOptions.value = val
  nextTick(() => {
    state.form.vice_pid = val.map((item: any) => item.id)
  })
}

const handleVicePidChange = (val: number[]) => {
  state.form.vice_pid = val
}

// 聚合商品的副SKU商品弹框 组件方法 end

// 聚合商品的组合售卖SKU商品弹框 组件方法 start
const DialogSalesPidsCheckedRef = ref<InstanceType<typeof PrimarPidDialog>>()

const handleOpenSalesPids = () => {
  nextTick(() => {
    if (!DialogSalesPidsCheckedRef.value) return
    DialogSalesPidsCheckedRef.value.dialogVisible = true

    const disabledVal = state.form.vice_pid
      .map((item: any) => ({ id: item }))
      .concat(state.form.primary_pid ? [{ id: state.form.primary_pid }] : []) // 主SKU商品 和 副SKU商品

    DialogSalesPidsCheckedRef.value.initialize(
      state.form.sales_pids ? state.form.sales_pids.map((item: any) => ({ id: item })) : [],
      disabledVal
    )
  })
}

const getExposeSalesPidsData = (val: any[]) => {
  if (!val || !val.length) return
  if (state.form.sales_pids && state.form.sales_pids !== val[0].id) {
  }
  salesPidsOptions.value = val
  nextTick(() => {
    state.form.sales_pids = val.map((item: any) => item.id)
  })
}

const handleSalesPidsChange = (val: number[]) => {
  state.form.sales_pids = val
}
// 聚合商品的组合售卖SKU商品弹框 组件方法 end

// 聚合商品的推荐SKU商品弹框 组件方法 start
// const DialogRecommendPidsCheckedRef = ref<InstanceType<typeof PrimarPidDialog>>() // 定义弹框引用

// const handleOpenRecommendPids = () => {
//   nextTick(() => {
//     if (!DialogRecommendPidsCheckedRef.value) return
//     DialogRecommendPidsCheckedRef.value.dialogVisible = true
//     DialogRecommendPidsCheckedRef.value.initialize(
//       state.form.recommend_pids
//         ? state.form.recommend_pids.map((item: any) => ({ id: Number(item) }))
//         : []
//     )
//   })
// }

// const getExposeRecommendPidsData = (val: any[]) => {
//   if (!val || !val.length) return
//   if (state.form.recommend_pids && state.form.recommend_pids !== val[0].id) {
//   }
//   recommendPidsOptions.value = val
//   nextTick(() => {
//     state.form.recommend_pids = val.map((item: any) => item.id)
//   })
// }

// const handleRecommendPidsChange = (val: number[]) => {
//   state.form.recommend_pids = val
// }
// 聚合商品的推荐SKU商品弹框 组件方法 end

// 聚合商品的商品主视频弹框 组件方法 start
const DialogPmvIdCheckedRef = ref<InstanceType<typeof Video>>() // 定义弹框引用

const handleOpenPmvId = () => {
  nextTick(() => {
    if (!DialogPmvIdCheckedRef.value) return
    DialogPmvIdCheckedRef.value.dialogVisible = true
    const disabledVal = state.form.smv_id
      ? state.form.smv_id.map((item: any) => ({ id: item }))
      : [] // 商品副视频
    DialogPmvIdCheckedRef.value.initialize(
      state.form.pmv_id ? [{ id: state.form.pmv_id }] : [],
      disabledVal //  (禁用)
    )
  })
}

const getExposePmvIdData = (val: any[]) => {
  if (!val || !val.length) return
  if (state.form.pmv_id && state.form.pmv_id !== val[0].id) {
  }
  pmvIdOptions.value = val.map((item) => ({
    id: item.id,
    name: item.video_title
  }))
  state.form.pmv_id = val[0].id
}

const handlePmvIdChange = (val: number) => {
  state.form.pmv_id = val
}
// 聚合商品的商品主视频弹框 组件方法 end

// 聚合商品的商品副视频弹框 组件方法 start
const DialogSmvIdCheckedRef = ref<InstanceType<typeof Video>>() // 定义弹框引用

const handleOpenSmvId = () => {
  nextTick(() => {
    if (!DialogSmvIdCheckedRef.value) return
    DialogSmvIdCheckedRef.value.dialogVisible = true
    const disabledVal = state.form.pmv_id ? [{ id: state.form.pmv_id }] : [] // 商品主视频
    DialogSmvIdCheckedRef.value.initialize(
      state.form.smv_id ? state.form.smv_id.map((item: any) => ({ id: Number(item) })) : [],
      disabledVal //  (禁用)
    )
  })
}

const getExposeSmvIdData = (val: any[]) => {
  if (!val || !val.length) return
  if (state.form.smv_id && state.form.smv_id !== val[0].id) {
  }
  smvIdOptions.value = val.map((item) => ({
    id: item.id,
    name: item.video_title
  }))
  nextTick(() => {
    state.form.smv_id = val.map((item: any) => item.id)
  })
}

const handleSmvIdChange = (val: number[]) => {
  state.form.smv_id = val
}
// 聚合商品的商品副视频弹框 组件方法 end

// 聚合商品的店铺弹框 组件方法 start
const DialogStorenameCheckedRef = ref<InstanceType<typeof DialogStorename>>() // 定义弹框引用

const handleOpenStorename = () => {
  nextTick(() => {
    if (!DialogStorenameCheckedRef.value) return
    DialogStorenameCheckedRef.value.dialogVisible = true
    DialogStorenameCheckedRef.value.initialize(state.form.storename ? state.form.storename : [])
  })
}

const getExposeStorenameData = (val: any[]) => {
  if (!val || !val.length) return

  state.form.storename = val

  state.inputDisplayText.storename = val.map((item: any) => item.label).join(',')
}
// 聚合商品的店铺弹框 组件方法 end

//上传成功以后回调
const handleUploadProductPhotoCallback = (val: any) => {
  state.product_photo_list.push(val)
  nextTick(() => {
    formRef.value?.validateField('product_photo')
  })
}
const handleUploadCloseshotsPhotoCallback = (val: any) => {
  state.closeshots_photo_list.push(val)
}

const handleRemoveProductPhotoFile = (val: any) => {
  if (state.product_photo_list && state.product_photo_list.length) {
    state.product_photo_list = state.product_photo_list.filter((item: Record<string, any>) => {
      item.uploadFile.uid !== val.uid
    })
  }
}
const handleRemoveCloseshotsPhotoFile = (val: any) => {
  if (state.closeshots_photo_list && state.closeshots_photo_list.length) {
    state.closeshots_photo_list = state.closeshots_photo_list.filter(
      (item: Record<string, any>) => {
        item.uploadFile.uid !== val.uid
      }
    )
  }
}
const handleProductPhotoPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}
const handleCloseshotsPhotoPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}
//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getFieldEnumApi({ field: 'all' })
  state.storenameList = resp.data.storename
}

const getSelectedSkuId = async () => {
  const resp = await getSelectedSkuIdApi({})
  selectedSkuIds.value = resp.data
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const params = { ...state.form } as unknown as Record<string, any>
      if (0 == params.primary_pid) {
        ElMessage.error('请选择主SKU商品')
        return
      }
      if (state.product_photo_list.length) {
        params.product_photo = state.product_photo_list.map((item: any) => item.id).join(',')
      }
      if (state.closeshots_photo_list.length) {
        params.closeshots_photo = state.closeshots_photo_list.map((item: any) => item.id).join(',')
      }
      const resp = await saveDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('order.createSucMsg'))
        if (state.source) {
          push(`${state.source}`)
        } else {
          push('/product/product-merge-management')
        }
      }
    }
  })
}

onMounted(() => {
  getDropDownBoxInfo()
  getSelectedSkuId()
})
</script>

<style lang="less" scoped>
.form-container {
  align-items: flex-start;

  :deep(.el-form-item__label) {
    display: inline-block;
    width: 100%; /* 继承label-width的宽度 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-align: right;
    text-overflow: ellipsis; /* 显示省略号 */
    white-space: nowrap; /* 禁止换行 */
  }
}
</style>
